var _url = "ws://" + ((location.hostname === "") ? '127.0.0.1' : location.hostname) + ":" + ((location.port == "")?'9000':location.port);
var _ws;
var _connected = false;
var _devInfos = null;
var _devNum = -1;
var _supportOcr = 0;
var _cropBox = null;
var _layoutReco = 0;
var _isStillPin = false;
var _instanceCB = null;
/**
 * 初始化webSocket连接
 */
function ConnectServer(callback, value) {
    if ('WebSocket' in window) {
        _ws = new WebSocket(_url);
    } else if (window.WebSocket) {
        _ws = new WebSocket(_url);
    } else if ('MozWebSocket' in window) {
        _ws = new MozWebSocket(_url);
    } else {
        alert(Lang.WS.lowVer);
    }
    _ws.onopen = function () {
        _connected = true;
        callback(value);
    }
    _ws.onclose = function (e) {
        _connected = false;
    }
    _ws.onmessage = function (e) {
        if (typeof e.data === "string") {
            onTxtMessage(e.data);
        } else {
            onBinMessage(e);
        }
    }
    _ws.onerror = function (e) {
        alert(Lang.WS.disConn)
    };
}


function getImgFileArray() {
  var fileArray = new Array();
  var trs = $('#tabBody tr');
  for (i = 0; i < trs.length; i++) {
    fileArray.push(_path + '\\' + trs[i].children[0].innerText);
  }
  return fileArray;
}

/**
 * 向服务器发送信息
 */
function SendTxt(jsonStr) {
    _connected ? _ws.send(jsonStr) : ConnectServer(SendTxt, jsonStr)
}
function SendJson(json) {
    _connected ? _ws.send(JSON.stringify(json)) : ConnectServer(SendJson, json)
}


// OCR识别
export function ocrFile() {
  // OCR识别
  var strLang ="Simplified chinese+English", strExtName = ".txt";
  var chkTxtOri =false;
  SendJson({func: 'FileOCR', language:strLang, extName:strExtName, detectTextOrientation:chkTxtOri,
    imagePath:"D:\\1666774536214.jpg", mode: 'path', reqId: new Date().getTime(),filePath:"D:\\OCR111.txt"});
  //displayOutputInfo(1, 'OCR识别中...');
}










function CropBox(pic){
 // this.imgObj = document.getElementById(imgId);
  console.log($('#pic').val()+"777")
  this.imgObj =$('#pic').val();
  //this.imgObj.draggable = false;
  // startX, startY 为鼠标点击时初始坐标
  this.startX = -1, this.startY = -1;
  // diffX, diffY 为鼠标初始坐标与 cropBox 左上角坐标之差，用于拖动
  this.diffX = -1, this.diffY = -1;
  // 是否拖动，初始为 false
  this.dragging = false;
  // 视频显示区rect
  this.rect = {left:0, top:0, right:0, bottom:0};
  // 视频显示区的上次位置
  this.lastPos = {x:0, y:0};
  this.overBox = null;
  this.onChange = null;
  this.onBuildInnerHtml = null;
  this.onGetBoxVal = null;
  this.enabled = false;
  _instanceCB = this;

  document.onselectstart = function() {
    return false;
  };

  this.enable = function(){
    // 鼠标按下
    document.onmousedown = function (e) {
      e = e || window.event;
      let t = e.target || e.srcElement;
      _instanceCB.getAreaRect();
      if (_instanceCB.inAreaRect(e)) {
        //console.log('imgObj.onmousedown inAreaRect', t.innerText);
        _instanceCB.startX = e.pageX;
        _instanceCB.startY = e.pageY;

        // 如果鼠标在 cropBox 上被按下
        if (t.className.match(/cropBox/)) {
          // 允许拖动
          _instanceCB.dragging = true;
          //console.log('this.dragging = true');

          // 设置当前 cropBox 的 id 为 moving_box
          if (document.getElementById("moving_box") !== null) {
            document.getElementById("moving_box").removeAttribute("id");
          }
          e.target.id = "moving_box";

          // 计算坐标差值
          _instanceCB.diffX = _instanceCB.startX - e.target.offsetLeft;
          _instanceCB.diffY = _instanceCB.startY - e.target.offsetTop;
        } else if (_instanceCB.isOverBoxChild(t)) {
          // 点击的cropBox的子元素
        } else {
          // 在页面创建 cropBox
          let active_box = document.createElement("div");
          active_box.id = "active_box";
          active_box.className = "cropBox";
          active_box.style.top = _instanceCB.startY + 'px';
          active_box.style.left = _instanceCB.startX + 'px';
          var html = '<a href="javascript:void(0)" onclick="_closeCropBox()" class="cropBox-close"></a>';
          if (_instanceCB.onBuildInnerHtml) {
            html = _instanceCB.onBuildInnerHtml(html);
          }
          active_box.innerHTML = html;
          document.body.appendChild(active_box);
          active_box = null;
        }
        e.stopPropagation();
      }
    };

    // 鼠标移动
    document.onmousemove = function (e) {
      // console.log('onmousemove _instanceCB.dragging=', _instanceCB.dragging);
      if (_instanceCB.dragging) {
        // 移动，更新 cropBox 坐标
        let mb = document.getElementById("moving_box");
        if (mb) {
          //console.log('moving_box == _instanceCB.overBox', _instanceCB.overBox == mb);
          //console.log(mb.style.cursor);
          let l, t, w, h;
          switch (mb.style.cursor) {
            case 'n-resize': //北(上)
              t = e.pageY, h = mb.clientHeight + (mb.offsetTop - e.pageY);
              if (h > 5 && t >= _instanceCB.rect.top && t < _instanceCB.rect.bottom - 5) {
                mb.style.top = t + 'px';
                mb.style.height = h + 'px';
              }
              break;
            case 'ne-resize': //东北(右上)
              t = e.pageY, w = e.pageX - mb.offsetLeft, h = mb.clientHeight + (mb.offsetTop - e.pageY);
              if (h > 5 && (mb.offsetTop + h) < _instanceCB.rect.bottom - 5 &&
                t >= _instanceCB.rect.top && t < _instanceCB.rect.bottom - 5) {
                mb.style.top = t + 'px';
                mb.style.height = h + 'px';
              }
              if (w > 5 && (mb.offsetLeft + w) < _instanceCB.rect.right - 5) {
                mb.style.width = w + 'px';
              }
              break;
            case 'e-resize': //东(右)
              w = e.pageX - mb.offsetLeft;
              if (w > 5 && (mb.offsetLeft + w) < _instanceCB.rect.right - 5) {
                mb.style.width = w + 'px';
              }
              break;
            case 'se-resize': //东南(右下)
              w = e.pageX - mb.offsetLeft, h = e.pageY - mb.offsetTop;
              if (w > 5 && (mb.offsetLeft + w) < _instanceCB.rect.right - 5) {
                mb.style.width = w + 'px';
              }
              if (h > 5 && (mb.offsetTop + h) < _instanceCB.rect.bottom - 5) {
                mb.style.height = h + 'px';
              }
              break;
            case 's-resize': //南(下)
              h = e.pageY - mb.offsetTop;
              if (h > 5 && (mb.offsetTop + h) < _instanceCB.rect.bottom - 5) {
                mb.style.height = h + 'px';
              }
              break;
            case 'sw-resize': //西南(左下)
              w = mb.clientWidth + (mb.offsetLeft - e.pageX), l = e.pageX, h = e.pageY - mb.offsetTop;
              if (l >= _instanceCB.rect.left && (l + w) < _instanceCB.rect.right - 5) {
                mb.style.width = w + 'px';
                mb.style.left = l + 'px';
              }
              if (h > 5 && (mb.offsetTop + h) < _instanceCB.rect.bottom - 5) {
                mb.style.height = h + 'px';
              }
              break;
            case 'w-resize': //西(左)
              w = mb.clientWidth + (mb.offsetLeft - e.pageX), l = e.pageX;
              if (w > 5 && l >= _instanceCB.rect.left && (l + w) < _instanceCB.rect.right - 5) {
                mb.style.width = w + 'px';
                mb.style.left = l + 'px';
              }
              break;
            case 'nw-resize': //西北(左上)
              if (e.pageY >= _instanceCB.rect.top && e.pageY < _instanceCB.rect.bottom - 5) {
                mb.style.height = mb.clientHeight + (mb.offsetTop - e.pageY) + 'px';
                mb.style.top = e.pageY + 'px';
              }
              if (e.pageX >= _instanceCB.rect.left && e.pageX < _instanceCB.rect.right - 5) {
                mb.style.width = mb.clientWidth + (mb.offsetLeft - e.pageX) + 'px';
                mb.style.left = e.pageX + 'px';
              }
              break;
            case '': //移动(中间)
              l = e.pageX - _instanceCB.diffX, t = e.pageY - _instanceCB.diffY;
              if (t >= _instanceCB.rect.top && (t + mb.offsetHeight) <= _instanceCB.rect.bottom) {
                mb.style.top = t + 'px';
              }
              if (l >= _instanceCB.rect.left && (l + mb.offsetWidth) <= _instanceCB.rect.right) {
                mb.style.left = l + 'px';
              }
              break;
          }
          e.stopPropagation();
        }
      } else {
        // 更新 cropBox 尺寸
        let ab = document.getElementById("active_box");
        if (ab) {
          if (e.pageX >= _instanceCB.rect.left && e.pageX < _instanceCB.rect.right - 5) {
            ab.style.width = e.pageX - _instanceCB.startX + 'px';
          }
          if (e.pageY >= _instanceCB.rect.top && e.pageY < _instanceCB.rect.bottom - 5) {
            ab.style.height = e.pageY - _instanceCB.startY + 'px';
          }
        } else {
          if (_instanceCB.overBox && _instanceCB.overBox.style.cursor != '' && _instanceCB.inOverBox(e)) {
            _instanceCB.overBox.style.cursor = '';
          }
        }
      }
    };

    // 鼠标抬起
    document.onmouseup = function (e) {
      //console.log('imgObj.onmouseup');
      // 禁止拖动
      _instanceCB.dragging = false;
      if (document.getElementById("active_box") !== null) {
        let ab = document.getElementById("active_box");
        ab.removeAttribute("id");
        // 如果长宽均小于 5px，移除 cropBox
        if (ab.offsetWidth < 10 || ab.offsetHeight < 10) {
          document.body.removeChild(ab);
        }
      }
      if (_instanceCB.onChange) {
        _instanceCB.onChange();
      }
    };

    document.onmouseover = function(e){
      e = e || window.event;
      let n = e.target || e.srcElement;
      if (window._lastNode != n && n.className == 'cropBox') {
        //console.log("onmouseover n=", n, "_instanceCB.overBox==null is ", _instanceCB.overBox==null);
        _instanceCB.overBox = n;
        let x = e.pageX - n.offsetLeft, y = e.pageY - n.offsetTop, dire = '';
        if (y >= 0 && y < 8) {
          dire += 'n';//北
        } else if (y > n.offsetHeight - 8 && y < n.offsetHeight + 8) {
          dire += 's';//南
        }
        if (x >= 0 && x < 8) {
          dire += 'w';//西
        } else if (x > n.offsetWidth - 8 && x < n.offsetWidth + 8) {
          dire += 'e';//东
        }
        //console.log(dire + '-resize');
        n.style.cursor = dire + '-resize';
        n.className += ' hover';
        //console.log('add hover');
      } else {
        if (_instanceCB.overBox) {
          if (n.parentNode != _instanceCB.overBox && n != _instanceCB.overBox && !_instanceCB.isOverBoxChild(n)) {
            _instanceCB.overBox.className = 'cropBox';
            _instanceCB.overBox.cursor = '';
            //console.log('onmouseover remove hover  _instanceCB.overBox = null');
            _instanceCB.overBox = null;
          }
        }
      }
    };

    this.enabled = true;
    this.displayCropBox('');
  };

  this.disable = function(){
    document.onmousedown = null;
    document.onmousemove = null;
    document.onmouseup = null;
    this.enabled = false;
    this.displayCropBox('none');
  };

  this.displayCropBox = function(val) {
    let ary = document.getElementsByClassName('cropBox');
    for (let i = 0; i < ary.length; i++) {
      ary[i].style.display = val;
    }
  };

  this.getAreaRect = function() {
    let e = this.imgObj, left = e.offsetLeft, top = e.offsetTop;
    while ((e = e.offsetParent) != null) {
      top += e.offsetTop;
      left += e.offsetLeft;
    }
    this.rect.left = left;
    this.rect.top = top;
    this.rect.right = left + this.imgObj.offsetWidth;
    this.rect.bottom = top + this.imgObj.offsetHeight;
  };

  // 用于视频框位置变化后调整裁切框的位置
  this.adjustPos = function() {
    if (this.enabled) {
      let x = this.rect.left, y = this.rect.top;
      this.getAreaRect();
      x = this.rect.left - x, y = this.rect.top - y;
      let boxes = document.getElementsByClassName('cropBox'), box = null, left, top;
      for (let j = 0; j < boxes.length; j++) {
        box = boxes[j];
        box.style.left = (parseInt(box.style.left) + x) + 'px';
        box.style.top = (parseInt(box.style.top) + y) + 'px';
      }
    }
  }

  this.inAreaRect = function(e) {
    return e.pageX >= this.rect.left && e.pageX <= this.rect.right && e.pageY >= this.rect.top && e.pageY <= this.rect.bottom;
  };

  this.inOverBox = function(e) {
    if (this.overBox) {
      let x = e.pageX - this.overBox.offsetLeft, y = e.pageY - this.overBox.offsetTop;
      return x > 8 && y > 8 && x < (this.overBox.offsetWidth - 8) && y < (this.overBox.offsetHeight - 8);
    }
    return false;
  };

  this.isOverBoxChild = function(obj) {
    if (this.overBox) {
      while (obj != undefined && obj != null && obj.tagName.toUpperCase() != 'BODY'){
        if (obj == this.overBox) {
          return true;
        }
        obj = obj.parentNode;
      }
    }
    return false;
  };

  // 获取CropBox的数组:[视频框的宽, 视频框的高, 框1的left, 框1的top, 框1的right, 框1的bottom, 框2的left, 框2的top, ....]
  // 各框的位置,以视频框的左上角为原点(0,0)
  this.getCropBoxArray = function() {
    this.getAreaRect();
    let ary = new Array(), i = 0;
    ary[i++] = this.imgObj.offsetWidth;
    ary[i++] = this.imgObj.offsetHeight;

    let boxes = document.getElementsByClassName('cropBox'), box = null, left, top;
    for (let j = 0; j < boxes.length; j++) {
      box = boxes[j];
      left = box.offsetLeft - this.rect.left;
      top = box.offsetTop - this.rect.top;
      ary[i++] = left;
      ary[i++] = top;
      ary[i++] = left + box.clientWidth;
      ary[i++] = top + box.clientHeight;
      if (this.onGetBoxVal) {
        this.onGetBoxVal(box, ary);
        i = ary.length;
      }
    }
    return ary;
  };
}

function _closeCropBox(e) {
  e = e || window.event;
  let a = e.target || e.srcElement;
  document.body.removeChild(a.parentNode);
  if (_instanceCB.onChange) {
    _instanceCB.onChange();
  }
}














/**
 * 处理服务器二进制消息
 */
function onBinMessage(e) {
    console.log('onBinMessage', e);
}

/**
 * 处理接收到的服务器文本消息
 */
function onTxtMessage(msg) {
    var jsonObj = JSON.parse(msg);
    if (jsonObj.result != 0 && jsonObj.result != 9) {
        // 返回result=0表示执行成功,其他值表示异常。9表示：设备使用中，打开摄像头时忽略这个异常
        console.log(jsonObj.func, jsonObj.errorMsg);
        message.run(jsonObj.func + "\t" + jsonObj.errorMsg,"warning",1700);
        //alert(jsonObj.func + "\r\n" + jsonObj.errorMsg);
    } else {
        switch (jsonObj.func) {
            case "GetCameraVideoBuff":
                DisplayVideo(jsonObj);
                break;
            case "GetCameraInfo":
                DisplayDevInfo(jsonObj.devInfo);
                //获取OCR支持信息(语言列表)
                GetOcrInfo();
                //获取曝光
                GetVideoParam();
                // 默认不启用USB按键
                OnExtButtonChange();
                break;
            case "GetOcrSupportInfo":
                DisplayOcrSupportInfo(jsonObj);
                break;
            case "CameraCapture":
                if (_layoutReco) {
                    _layoutReco = 0;
                    $("#resultArea").val(Lang.cam.layoutRrecoing);
                    SendJson({func: 'RecogLayout', type: 0, mime: jsonObj.mime, imageBase64: jsonObj.imgBase64[0], reqId: new Date().getTime()});
                }
                for (var i = 0; i < jsonObj.imgBase64.length; i++) {
                  console.log(jsonObj.imgBase64[0]+"path")
                    DisplayImg(jsonObj.mime, jsonObj.imgBase64[i]);
                }
                //message.run(jsonObj.func + "\t" + "成功","success",1500);
                break;
            case "RecogLayout":
                DisplayLayoutResult(jsonObj);
                break;
            case "RecogBarCode":
                DisplayBarCodeResult(jsonObj);
                break;
            case "Notify":
                // 收到通知
                if (jsonObj.event == "OnUsbKeyPress") {
                    // 收到USB按键按下的通知
                    // {"func":"Notify","event":"OnUsbKeyPress","reqId":1636099207839.0,"result":0,"time":"1636099214"}
                    DisplayUsbKeyPress(jsonObj);
                } else if (jsonObj.event == "OnDeviceChanged") {
                    // 设备有变化,格式如下:
                    // {"func":"Notify","event":"OnDeviceChanged","devName":"\\\\?\\USB#VID_0C45&PID_6366...","func":"OnDeviceChanged","result":0,"type":1}
                    // type: 1设备插入; 2设备已拔出
                    GetCameraInfo();
                }
                break;
            case "SetCameraInfo":
            case "SetStillPinInfo":
                message.run("切换分辨率成功","success",1500);
                break;
            case "GetVideoParameter":
                displayExpInfo(jsonObj.param);
            default:
                console.log(msg);
                break;
        }
    }
}

// 获取设备信息
function GetCameraInfo() {
    SendTxt('{"func":"GetCameraInfo","reqId":"' + new Date().getTime() + '"}');
}

// 获取OCR支持信息
function GetOcrInfo() {
    SendTxt('{"func":"GetOcrSupportInfo","reqId":"' + new Date().getTime() + '"}');
}

function GetVideoParam(){
    var reqId = new Date().getTime();
    var cmd = JSON.stringify({func: 'GetVideoParameter', reqId: reqId, devNum: _devNum});
    SendTxt(cmd);
}

export function SetVideoParam(){
    var reqId = new Date().getTime();
    var exp = parseInt($("#export").val());
    var flg = 0;
    var cmd = JSON.stringify({func: 'SetVideoParameter', reqId: reqId, devNum: _devNum, value:exp, flag:flg});
    SendTxt(cmd);
}

function displayExpInfo(v){
    document.getElementById("export").setAttribute("min", v.min) ;
    document.getElementById("export").setAttribute("max", v.max) ;
    document.getElementById("export").setAttribute("value", v.value) ;
    document.getElementById("expCheck").setAttribute("value", v.flag) ;
    // $("#export").min = v.min;
    // $("#export").max = v.max;
    // $("#export").value = v.value;
    // $("#expCheck").value = v.flag;
}

//显示条码识别结果
function DisplayBarCodeResult(jsonObj) {
    if (jsonObj.codeInfos) {
        var a = jsonObj.codeInfos;
        var s = Lang.cam.res + "\r\n";
        for (var i = 0; i < a.length; i++) {
            s += Lang.cam.content + a[i].codeNum + "\r\n";
            s += Lang.cam.type + a[i].codeType + "\r\n";
            s += "--------\r\n"
        }
        $("#resultArea").val(s);
    } else {
        $("#resultArea").val(Lang.cam.noRrecognized);
    }
}

//显示版面识别结果
function DisplayLayoutResult(v) {
    if (v.response) {
        var s = "";
        var resp = v.response;
        if (resp.result) {
            if (typeof(resp.result) === 'object') {
                for (var key in resp.result){
                    s += key;
                    s += ": ";
                    s += resp.result[key];
                    s += "\r\n";
                }
            } else {
                s += resp.result;
            }
        } else {
            s = Lang.cam.errLayout + "\r\n" + resp.str + "  " + resp.errMsg;
        }
        $("#resultArea").val(s);
    } else {
        $("#resultArea").val(s = Lang.cam.errLayout + "\r\n" + v.errorMsg);
    }
}

function DisplayUsbKeyPress(v) {
    var str = $("#resultArea").val();
    $("#resultArea").val(Lang.MSG.usbKeyPress + " time:" +  v.time + "\r\n" + str);
}

var _w = 0, _h = 0;
function DisplayVideo(v) {
    if (v.imgBase64Str) {
        if (_w != v.width || _h != v.height) {
            //设置视频显示的宽高（宽度控制为640px）
            if (v.width > v.height) {
                $("#pic").css('width', '640px').css('height', Math.ceil(640 * v.height / v.width) + 'px');
            } else {
                $("#pic").css('height', '640px').css('width', Math.ceil(640 * v.width / v.height) + 'px');
            }
            _w = v.width, _h = v.height;
        }
        //显示视频
        document.getElementById("pic").src = "data:" + v.mime + ";base64," + v.imgBase64Str;
    }
}

function DisplayDevInfo(devInfos) {
    _devInfos = devInfos;
    if (_devInfos == null || _devInfos.length == 0) {
        alert(Lang.cam.doc);
        return;
    }
    //初始化设备信息
    displayCamera();
    displayMediaType();
    displayResolution();

    switchCameraInfo_Fun();
}

function DisplayOcrSupportInfo(v) {
    if (v.languages) {
        // 支持orc, 允许‘自动文字方向’
        _supportOcr = 1;
        document.getElementById('opOcrDirection').disabled = false;

        var obj = document.getElementById("language");
        obj.options.length = 0;
        for (var i = 0; i < v.languages.length; i++) {
            // 语言ID是从1开始
            obj.options.add(new Option(v.languages[i], i + 1));
        }
        // 默认选中'Simplified chinese+English'
        obj.selectedIndex = 98;
    }
}

//初始化信息
$(function () {
    //获取摄像头设备列表
    GetCameraInfo();

    window.onresize = onWinResize;
    onWinResize();

    _cropBox = new CropBox("pic");

})

function onWinResize() {
    console.log('onWinResize()');
    //初始化图片列表的高度
    $("#right_div").css('height', (document.body.clientHeight - 30) + 'px');
    //初始化'结果显示'的高度
    var p = $("#resultArea").offset();
    $("#resultArea").css('height', (document.body.clientHeight - p.top - 16) + 'px');

    var cropType = parseInt($("#crop_type").val());
    if (cropType == 3) {
        showMiddleLine_Fun(cropType);
    }
    if (_cropBox) {
        _cropBox.adjustPos();
    }
}

//设备信息的onchange事件
export function switchCameraInfo_Fun() {
    var reqId = new Date().getTime();
    if (_devNum >= 0) {
        //关闭之前的摄像头
        SendTxt('{"func":"CloseCamera","reqId":"' + reqId + '","devNum":' + _devNum + '}');
    }

    //刷新显示 视频格式 下拉列表
    displayMediaType();

    //刷新显示 分辨率下拉列表
    displayResolution();

    //开启摄像头
    _devNum = $("#cameraInfo").val() == null ? 0 : parseInt($("#cameraInfo").val());
    reqId++;
    var cmd = '{"func":"OpenCamera","reqId":"' + reqId + '","devNum":' + _devNum + ',"mediaNum":0,"resolutionNum":0,"fps":5}';
    SendTxt(cmd);
console.log("88888888888888888")
    // 获取预览视频
    reqId++;
    cmd = '{"func":"GetCameraVideoBuff","reqId":"' + reqId + '","devNum":' + _devNum + ',"enable":"true"}';
    SendTxt(cmd);
}

export function cameraCapture_Fun(path) {
    //设置图像算法

    setCameraImageInfo_Fun();
  var reqId = new Date().getTime();
    //高拍仪拍照接口
  var cmd = JSON.stringify({func: 'CameraCapture', reqId: reqId, devNum: _devNum, mode: 'base64;path',imagePath: path});
 console.log(cmd+"cmd")
  SendTxt(cmd);
}

function cameraCaptureIdPhone() {
    //设置图像算法
    setCameraImageInfo_Fun();
    //高拍仪拍照接口
    var reqId = new Date().getTime();
    var cmd = JSON.stringify({func: 'CameraCapture', reqId: reqId, devNum: _devNum, mode: 'base64', IdPhoto: {bgColor: $("#bgColor").val()}});
    SendTxt(cmd);
}

function layoutRecognition() {
    // 设置单图裁切
    var rotateAngle = parseInt($("#rotateType").val());
    var langId = parseInt($("#language").val());
    var reqId = new Date().getTime();
    var cmd = {func:'SetCameraImageInfo', reqId:reqId, devNum:_devNum, cropType:1, imageType:0, fillBorderType:0,
         removalForeign:0, rotate:rotateAngle, textOrientationLangId:langId};
    SendJson(cmd);

    // 拍照
    reqId++;
    _layoutReco = 1;
    SendJson({func: 'CameraCapture', reqId: reqId, devNum: _devNum, mode: 'base64'});
}

function recogBarCode_Fun() {
    $("#resultArea").val(Lang.cam.bar);
    var reqId = new Date().getTime();
    var cmd = JSON.stringify({'func': 'RecogBarCode', 'reqId':reqId, 'devNum':_devNum});
    SendTxt(cmd);
}


// 刷新显示 设备名称 下拉列表
function displayCamera() {
    var obj = document.getElementById("cameraInfo");
    var lastSelectedIndex = obj.options.selectedIndex;
    obj.options.length = 0;
    for (var i = 0; i < _devInfos.length; i++) {
        obj.options.add(new Option(_devInfos[i].devName, _devInfos[i].id));
    }
    if (lastSelectedIndex >= 0 && lastSelectedIndex < _devInfos.length) {
        obj.options.selectedIndex = lastSelectedIndex;
    }
}

// 刷新显示 视频格式 下拉列表
function displayMediaType() {
    var index1 = document.getElementById("cameraInfo").options.selectedIndex;
    var mediaTypes = _devInfos[index1].mediaTypes;
    var obj = document.getElementById("mediaType");
    obj.options.length = 0;
    if(_devInfos[index1].stillPin != undefined) {
        obj.options.add(new Option(_devInfos[index1].stillPin.mediaType, 0));
    }
    else {
        for (var i = 0; i < mediaTypes.length; ++i) {
            obj.options.add(new Option(mediaTypes[i].mediaType, i));
        }
    }
}

// 刷新显示 分辨率下拉列表
function displayResolution() {
    var index1 = document.getElementById("cameraInfo").options.selectedIndex;
    var index2 = document.getElementById("mediaType").options.selectedIndex;
    var obj = document.getElementById("resolution");
    //清空resolution:select数据
    obj.options.length = 0;
    if(_devInfos[index1].stillPin != undefined) {
        _isStillPin = true;
        var SPresolutions = _devInfos[index1].stillPin.resolutions;
        for (var i = 0; i < SPresolutions.length; i++) {
            obj.options.add(new Option(SPresolutions[i], i));
        }
    }
    else{
        _isStillPin = false;
        var resolutions = _devInfos[index1].mediaTypes[index2].resolutions;
        for (var i = 0; i < resolutions.length; i++) {
            obj.options.add(new Option(resolutions[i], i));
        }
    }
}

//设置设备信息
export function setCameraInfo_Fun() {
    //分辨率的值
    var resolutionNum = $("#resolution").val() == null ? 0 : parseInt($("#resolution").val());
    var mediaNum = $("#mediaType").val() == null ? 0 : parseInt($("#mediaType").val());
    var reqId = new Date().getTime();
    var cmd;
    if(_isStillPin){
        cmd = JSON.stringify({'func': 'SetStillPinInfo', 'reqId':reqId, 'devNum':_devNum, 'resolutionNum': resolutionNum});
    }
    else{
        cmd = JSON.stringify({'func': 'SetCameraInfo', 'reqId':reqId, 'devNum':_devNum, 'mediaNum':mediaNum,'resolutionNum': resolutionNum});
    }
    SendTxt(cmd);
}

//放大
export function zoomin()
{
  //var obj1=document.getElementById("curDev");
  var obj1=$("#cameraInfo").val()
  var idx = obj1.selectedIndex;
  var cmd = JSON.stringify({func: 'VideoZoom',  index:idx, flag:1});
  SendTxt(cmd);
}
/**设置图像算法
 CropType 裁切：0-不裁切  1-单图裁切　２－多图裁切　３－曲面矫正
 ImageType 图像效果：0-彩色原色 1-灰度图片 2-黑白文档　３－　彩色文档　４－红印文档　５－蓝印文档　６－彩色照片　７－票据增强
 FillBorderType 补边：0-不填充 1-自动填充白色　２－自动填充周边色
 RemovalForeign 异物去除　０-无　1-去除手指　２－去除装订孔
 **/
export function setCameraImageInfo_Fun() {
    var cropType = parseInt($("#crop_type").val());
    //曲面矫正需要显示中间绿色线条
/*    showMiddleLine_Fun(cropType);
    // 控制自定义裁切框的显示
    allowCropBox(cropType);

    var fillBorderType = parseInt($("#fill_border").val());
    var removalForeign = parseInt($("#foreign_remove").val());*/
    var rotateAngle = parseInt($("#rotateType").val());
  var imageType = parseInt($("#image_type").val());
/*    var langId = parseInt($("#language").val());

    var dpi = parseInt($("#dpi").val());*/
  var reqId = new Date().getTime();
  var fillBorderType = parseInt($("#fill_border").val());
 // var fillBorderType = 0;
  var removalForeign =0;
  var langId = 0;

  var dpi = parseInt($("#dpi").val());
    console.log("8")

  //曲面矫正需要显示中间绿色线条
  //showMiddleLine_Fun(cropType);
  // 控制自定义裁切框的显示
  //allowCropBox(cropType);
  console.log("9")
  _cropBox = new CropBox("pic");
    var cropBoxArray = null;
    if (cropType == 9) {
        cropBoxArray = _cropBox.getCropBoxArray();
        if (cropBoxArray.length < 6) {
            // 设置了自定义裁切，但还没有画裁切框，则按‘不裁切’处理
            cropType = 0;
            cropBoxArray = null;
        }
    }

    var cmd = {func:'SetCameraImageInfo', reqId:reqId, devNum:_devNum, cropType:cropType,
        imageType:imageType, fillBorderType:fillBorderType, removalForeign:removalForeign, rotate:rotateAngle,
        textOrientationLangId:langId, dpi:dpi};
    if (cropBoxArray) {
        cmd.posArray = cropBoxArray;
    }

    SendTxt(JSON.stringify(cmd));
}

export function OnRotateChange() {
    /*if (_supportOcr) {
      console.log($("#rotateType").val()+"zhi")
        $("#language").parent().css('display', $("#rotateType").val().selectedIndex == 4 ? '' : 'none');
        var p = $("#resultArea").offset();
        $("#resultArea").css('height', (document.body.clientHeight - p.top - 10) + 'px');
    }*/
    console.log("878787")
    setCameraImageInfo_Fun();
  console.log("8787879")
}

export function tuxiang() {

  setCameraImageInfo_Fun();

}

export function dpi() {

  setCameraImageInfo_Fun();

}


function OnExtButtonChange() {
    var cbFun = $("#selExtButton").val();
    var cmd = {func: 'ExternalButton', reqId: new Date().getTime()};
    if (cbFun == "None") {
        cmd.enable = false;
    } else {
        cmd.enable = true;
        cmd.callbackFunc = cbFun;
        // 补充各角发命令的其他属性
        switch (cbFun) {
            //Notify,CameraCapture,CameraCaptureBook,RecogBarCode
            case 'CameraCapture':
                cmd.devNum = _devNum;
                cmd.mode = 'base64';
                break;
            case 'RecogBarCode':
                cmd.devNum = _devNum;
                break;
        }
    }
    SendJson(cmd);
}

//曲面矫正需要显示中间绿色线条
 export function showMiddleLine_Fun(cropType) {
    if (cropType == 3) {
        var obj = $("#pic");
        var p = obj.offset(), w = obj.width(), h = obj.height();
        $("#vertical-line").css('top', p.top + 'px').css('left', (p.left + w/2 - 2) + 'px').css('height', h + 'px').css('display','');
        $("#vertical-line").show();
    } else {
        $("#vertical-line").hide();
    }
}

// 控制自定义裁切框的显示
export function allowCropBox(cropType) {
    if (cropType == 9) {
        _cropBox.enable();
    } else {
        _cropBox.disable();
    }
}

//添加图片项
function DisplayImg(mime, imgBase64Str) {
    var h = '<div><img width="100%" src="' + 'data:' + mime + ';base64,' + imgBase64Str + '"></div>';
   console.log(imgBase64Str+"imgBase64Str")
   console.log(mime+"mime")
    $("#image_data").prepend(h);
}

// 清空图片展示列表
export function clearImageFile() {
    $("#image_data").empty();
}

